package com.atguigu.vod.service.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.atguigu.vod.service.service.VodService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.vod.service.utils.ConstantPropertiesUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

import static com.atguigu.vod.service.utils.InitVodClient.initVodClient;

/**
 * @Author: Cyrus
 * @CreateDate: 2020/12/10
 */
@Service
public class VodServiceImpl implements VodService {


    @Override
    public String uuploadAliyunVideop(MultipartFile file) {
        try {
            /**
             * title：显示名称
             * fileName:上传的文件原始名称
             * inputStream：文件输入流
             */
            String fileName = file.getOriginalFilename();
            String title = fileName.substring(0, fileName.lastIndexOf("."));
            InputStream inputStream = file.getInputStream();
            UploadStreamRequest request = new UploadStreamRequest(
                    ConstantPropertiesUtils.KEY_ID,
                    ConstantPropertiesUtils.KEY_SECRET,
                    title,
                    fileName,
                    inputStream);

            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            String videoId = "";
            if (response.isSuccess()) {
                videoId = response.getVideoId();
            } else {
                videoId = response.getVideoId();
            }
            return videoId;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public void removeAliyunVideo(String id) {
        try {
            DefaultAcsClient client = initVodClient(ConstantPropertiesUtils.KEY_ID, ConstantPropertiesUtils.KEY_SECRET);
            //创建删除视频的request
            DeleteVideoRequest request = new DeleteVideoRequest();
            //支持传入多个视频ID，多个用逗号分隔
            request.setVideoIds(id);
            //删除视频
            client.getAcsResponse(request);
        } catch (Exception e) {
            throw new GuliException(20001, "删除视频失败");
        }
    }
}